package io.gitee.zhangbinhub.admin.component

import io.gitee.zhangbinhub.admin.constant.AcpConstant
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.stereotype.Component

/**
 * @author zhangbin by 11/04/2018 15:19
 * @since JDK 11
 */
@Component
class BasicUserDetailsService : UserDetailsService {
    private val users: MutableMap<String, String> = HashMap()

    init {
        users[AcpConstant.resourceServerClientId] = AcpConstant.resourceServerClientSecret
    }

    /**
     * 根据 username 获取用户信息
     *
     * @param username 用户名
     * @return 用户对象
     * @throws UsernameNotFoundException 找不到用户信息异常
     */
    @Throws(UsernameNotFoundException::class)
    override fun loadUserByUsername(username: String): UserDetails {
        val grantedAuthorities: MutableSet<GrantedAuthority> = HashSet()
        grantedAuthorities.add(SimpleGrantedAuthority("ROLE_ACTUATOR")) //角色编码
        val password = if (users.containsKey(username)) {
            users[username]
        } else {
            throw UsernameNotFoundException("Basic用户名【$username】无效!")
        }
        return User(username, password, true, true, true, true, grantedAuthorities)
    }
}
